import { defineStore } from 'pinia'
import { getCart, addCartItem, updateCartItem, deleteCartItem, batchDeleteCartItems, clearCart, mergeCart, batchCheckout } from '@/utils/request'

export const useCartStore = defineStore('cart', {
  state: () => ({
    cartList: [],      // 购物车商品列表
    loading: false,    // 加载状态
  }),
  getters: {
    // 选中的商品
    selectedItems: (state) => state.cartList.filter(item => item.selected),
    // 购物车总价
    totalPrice: (state) => state.cartList
      .filter(item => item.selected)
      .reduce((sum, item) => sum + Number(item.subtotal), 0),
    // 是否全选
    allChecked: (state) => state.cartList.length > 0 && state.cartList.every(item => item.selected),
  },
  actions: {
    // 获取购物车列表
    async fetchCart() {
      this.loading = true
      try {
        const res = await getCart()
        // 后端直接返回数组，不需要res.data
        this.cartList = Array.isArray(res) ? res : []
      } finally {
        this.loading = false
      }
    },
    // 添加商品到购物车
    async addToCart(productId, quantity = 1) {
      await addCartItem({ productId, quantity })
      await this.fetchCart()
    },
    // 更新购物车商品（数量/选中状态）
    async updateCart(itemId, quantity, selected) {
      await updateCartItem({ itemId, quantity, selected })
      await this.fetchCart()
    },
    // 删除单个商品
    async removeItem(itemId) {
      await deleteCartItem({ itemId })
      await this.fetchCart()
    },
    // 批量删除
    async batchRemove(itemIds) {
      await batchDeleteCartItems(itemIds)
      await this.fetchCart()
    },
    // 清空购物车
    async clear() {
      await clearCart()
      await this.fetchCart()
    },
    // 合并本地购物车
    async merge(localItems) {
      await mergeCart(localItems)
      await this.fetchCart()
    },
    // 批量结算
    async checkout(itemIds) {
      await batchCheckout(itemIds)
      await this.fetchCart()
    },
    // 切换全选
    toggleAll(checked) {
      this.cartList.forEach(item => {
        item.selected = checked
      })
    },
    // 切换单个选中
    toggleItem(itemId, checked) {
      const item = this.cartList.find(i => i.itemId === itemId)
      if (item) item.selected = checked
    }
  }
}) 